﻿#include "Friend.h"
#include "TcpClient.h"

Friend::Friend(QWidget* parent)
	: QWidget(parent) {
	//显示信息
	m_pShowMsgTE = new QTextEdit;
	//显示好友列表
	m_pFriendListWidget = new QListWidget;
	//显示信息输入框
	m_pInputMsgLE = new QLineEdit;

	//删除好友
	m_pDelFriendPB = new QPushButton("删除好友");
	//刷新好友列表
	m_pFlushFriendPB = new QPushButton("刷新好友列表");
	//查看在线的用户
	m_pShowOnlineUsrPB = new QPushButton("显示在线用户");
	//查找用户
	m_pSearchUsrPB = new QPushButton("查找用户");
	//发送按钮
	m_pMsgSendPB = new QPushButton("发送");
	//私聊按钮
	m_pPrivateChatPB = new QPushButton("私聊");

	//显示在线用户列表
	m_pOnline = new Online;

	//生成右侧垂直布局(5个按钮)
	QVBoxLayout* pRightPBVBL = new QVBoxLayout;
	pRightPBVBL->addWidget(m_pDelFriendPB);
	pRightPBVBL->addWidget(m_pFlushFriendPB);
	pRightPBVBL->addWidget(m_pShowOnlineUsrPB);
	pRightPBVBL->addWidget(m_pSearchUsrPB);
	pRightPBVBL->addWidget(m_pPrivateChatPB);

	//生成顶部水平布局(信息与四个按钮)
	QHBoxLayout* pTopHBL = new QHBoxLayout;
	pTopHBL->addWidget(m_pShowMsgTE);
	pTopHBL->addWidget(m_pFriendListWidget);
	pTopHBL->addLayout(pRightPBVBL);

	//生成下部水平布局
	QHBoxLayout* pMsgHBL = new QHBoxLayout;
	pMsgHBL->addWidget(m_pInputMsgLE);
	pMsgHBL->addWidget(m_pMsgSendPB);

	//生成总体垂直布局
	QVBoxLayout* pMain = new QVBoxLayout;
	pMain->addLayout(pTopHBL);
	pMain->addLayout(pMsgHBL);
	pMain->addWidget(m_pOnline);
	//默认隐藏，点击在线用户后显示
	m_pOnline->hide();

	//实际生成
	setLayout(pMain);

	//添加信号\槽
	connect(m_pShowOnlineUsrPB, SIGNAL(clicked()),
		this, SLOT(showOnline()));
	connect(m_pSearchUsrPB, SIGNAL(clicked()),
		this, SLOT(searchUsr()));
}

void Friend::showAllOnlineUsr(PDU* pdu) {
	if (pdu == NULL) {
		return;
	}
	m_pOnline->showUsr(pdu);
}

void Friend::searchUsr() {
	QString inputName = QInputDialog::getText(this, "搜索用户名", "用户名");
	if (inputName.isEmpty()) {	//输入为空
		QMessageBox::information(this, "搜索用户", "输入用户名不能为空");
		return;
	}
	if (inputName.toLocal8Bit().size() >= 32) {	//输入过长
		QMessageBox::information(this, "搜索用户", NAME_OVERLONG);
		return;
	}
	PDU* pdu = mkPDU(0);
	pdu->uiMsgType = ENUM_MESSAGE_TYPE_SEARCH_USER_REQUEST;
	memcpy(pdu->caData, inputName.toLocal8Bit().data(), inputName.toLocal8Bit().size());
	TcpClient::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen);
	free(pdu);
	pdu = NULL;
}

void Friend::showOnline() {
	if (m_pOnline->isHidden()) {
		m_pOnline->show();
		PDU* pdu = mkPDU(0);
		pdu->uiMsgType = ENUM_MESSAGE_TYPE_ALL_ONLINE_REQUEST;
		TcpClient::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen);
		free(pdu);
		pdu = NULL;
	}
	else {
		m_pOnline->hide();
	}
}